/**
 * 卖家留言弹出框
 */

import React, { Component } from 'react';
import { Modal, Input } from 'antd';
import noop from 'util/noop'
class MessageDialog extends Component {


    static defaultProps = {
        visible:false,
        onOk:noop,
        onCancel:noop,
    }
    
    constructor(props) {
        super(props);
        this.MAX_NUM = 300;

        this.state = {
            content:'',
            less:this.MAX_NUM,
            errorMsg:''
        }
    }

    componentWillReceiveProps(nextProps) {
        if(!nextProps.visible){
            this.setState(()=>{
                return {
                    content:'',
                    less:this.MAX_NUM,
                    errorMsg:''
                }
            })
        }
    }
    
    render() {
        const { visible, onOk, onCancel, ...rest }  = this.props;

        const { content, less, errorMsg } = this.state;
        return (
            <Modal
                visible={visible}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                {...rest}
            >
                <p className="pushb">{`可输入${less}字`}</p>
                <Input type="textarea" rows={4} maxLength={300} onChange={this.handleChange} value={content} />

                <p className="t-red pusht">{errorMsg}</p>
            </Modal>
        );
    }

    handleChange = (e) => {
        this.setState({
            content:e.target.value,
            less:this.MAX_NUM - e.target.value.length,
            errorMsg:'',
        })
    }

    handleOk = () => {
        const { content } = this.state;
        if(content.trim() && content.length <= this.MAX_NUM){
            this.props.onOk(content);
        }else{
            if(!content.trim()){
                this.setState({
                    errorMsg:'请输入留言内容！'
                })
            }else if(content.length >this.MAX_NUM){
                this.setState({
                    errorMsg:'留言内容最多300字！'
                })
            }
            
        }
    }

    handleCancel = () => {
        this.props.onCancel();
    }
}

export default MessageDialog;